import React, { Component } from 'react'
import { Button, Card, Table, message, Modal, Form, Input } from 'antd';
import {connect} from "react-redux"
import { PlusCircleOutlined } from '@ant-design/icons';
import { reqCategory, reqAddCategory, reqUpdateCategory } from "../../api/index"
import { PAGE_SIZE } from "../../config/index"
import {createSaveCategoryAction} from "../../redux/actions/category_action"

class Category extends Component {


    state = {
        categoryList: [], //商品分类列表
        visible: false,
        handleType: '',
        isLoading: true,
        currentId:"",
        currentName:""
    }

    //获取分类
    getCategory = async () => {
        let result = await reqCategory()
        this.setState({ isLoading: false })
        const { status, data, msg } = result
        if (status === 0) {
            this.setState({categoryList: data.reverse()})
            this.props.saveCategory(data)
        }
        else message.error(msg, 1)
    }

    componentDidMount() {
        this.getCategory()
    }

    //处理模态框
    showAddModal = () => {
        this.setState({
            handleType: 'add',
            currentId:"",
            currentName:"",
            visible: true,
            
        });
    };
    showUpdateModal = (categoryObj) => {
        let currentId = categoryObj._id
        let currentName = categoryObj.name  
        this.setState({
            handleType: 'update',
            visible: true,
            currentId,
            currentName
        });
    };


    //添加商品逻辑【被抽离出来的】
    toAdd = async (value) => {
        //请求添加分类
        let result = await reqAddCategory(value)
        const { status, data, msg } = result
        if (status === 0) {
            message.success("添加分类成功!")
            let newState = [data, ...this.state.categoryList]
            this.setState({ categoryList: newState })
            this.form.resetFields()   //表单重置          【注意】：这两项重置和隐藏，只有当用户确确实实添加成功了之后在做
            this.setState({ visible: false })  //隐藏模态框         失败了就把模态框停那，让用户修改
        }
        if (status === 1) message.error(msg, 1)
    }
    //更新商品逻辑【被抽离出来的】
    toUpdate = async (categoryId, categoryName) => {
        let result = await reqUpdateCategory(categoryId, categoryName)
        const { status, msg } = result
        if (status === 0) {
            message.success('更新分类名称成功!', 1)
            this.form.resetFields()  //表单重定 
            this.setState({
                visible: false,
            })
            this.getCategory()  //重新获取分类列表，当做刷新一次
        }
        if (status === 1) message.error(msg, 1)

    }
    handleOk = () => {
        // 统一验证表单(field)
        this.form.validateFields()
            .then(value => {
                if (this.state.handleType === 'add') this.toAdd(value.categoryName)
                if (this.state.handleType === 'update') this.toUpdate(this.state.currentId, value.categoryName)
            })
            .catch(err => {
                message.warn('您输入的有误，请重新输入')
            })

    };
    handleCancel = () => {
        this.form.resetFields()  //表单重定 
        this.setState({
            visible: false,
        });
    };

    render() {
        const { visible } = this.state;
        const dataSource = this.state.categoryList
        const columns = [
            {
                title: '分类名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '操作',
                // dataIndex: 'categoryName', (不要这一项，传过来a的参数为一整个对象)
                key: 'age',
                render: (categoryObj) => { return <Button onClick={() => { this.showUpdateModal(categoryObj) }} type='link'>修改分类</Button> },
                width: "25%",
                align: "center"
            }
        ];
        return (
            <>
                <Card extra={<Button onClick={this.showAddModal} size='large' type='primary'><PlusCircleOutlined />添加</Button>}>
                    <Table rowKey="_id" loading={this.state.isLoading} pagination={{ showQuickJumper: true, pageSize: PAGE_SIZE }} bordered={true} dataSource={dataSource} columns={columns} />
                </Card>
                <Modal
                    title={<div>{this.state.handleType === 'add' ? '添加分类' : '修改分类'}</div>}
                    visible={visible}
                    cancelText="取消"
                    okText="确认"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >

                    <Form
                        name="normal_login"
                        className="login-form"
                        initialValues={{ remember: true }}
                        ref={c => this.form = c}
                    >
                        <Form.Item
                            name="categoryName"
                            rules={[{ required: true, message: '请必须输入你的分类名!' }]}
                            initialValue={this.state.currentName}   //【坑】
                        >
                            <Input placeholder="请输入分类名" />
                        </Form.Item>
                    </Form>

                </Modal>
            </>
        )
    }
}

export default connect(
    state => ({}),
    {saveCategory:createSaveCategoryAction}
)(Category)